<?php

define("_FIELD_SOURCE_DB"                     , 0);
define("_FIELD_TYPE_STRING"                   , "STRING");
define("_FIELD_TYPE_NUMBER"                   , "NUMBER");

class ComposerQueryV2{

  /**
   * Error handler
   *
   * @var Misc
   */
  public $ErrHdl;

  /**
   * init error handler
   *
   * @param Misc $ErrHdl
   */
  function initErrorHandler(&$ErrHdl){

    $this->ErrHdl = &$ErrHdl;
  }

  /**
   * add a comma
   * if idx is not equal to $max
   *
   * @param integer $idx
   * @param integer $max
   * @return string
   */
  function addComma($idx, $max){

    /**
     * if we still have another entry then add comma
     */
    if($idx != ($max-1)){

      return ",";
    }else{

      return "";
    }
  }

  /**
   * Compose insert query and exec
   *
   * @param Database  $Db
   * @param string    $keyName   key of table name
   * @param Composer  $SourceDb  ComposerSourceDbV2 or above
   */
  function insertExecQuery(&$Db,
                           &$keyName,
                           &$SourceDb){

    $srcDb        = $SourceDb->fetchValue($keyName);

    /**
     * get the key index
     */
    $idx          = $SourceDb->getKeyIndex($keyName);

    $szField      = $SourceDb->getSzField($idx);

    $lstField     = $SourceDb->getLstField($idx);

    $szFieldType  = $SourceDb->getSzField($idx);

    $lstFieldType = $SourceDb->getLstField($idx);

    $lstData      = $SourceDb->getLstData($idx);

    $query =  "INSERT INTO ".$srcDb." ( ";

    for($iField = 0; $iField < $szField; $iField++){

      $query .= $lstField[$iField];

      $query .= $this->addComma($iField, $szField);
    }

    $values = "";

    for($iFieldType = 0; $iFieldType < $szFieldType; $iFieldType++){

      switch($lstFieldType[$iFieldType]){

        /**
         * with "'"
         */
        case _FIELD_TYPE_STRING:

          $values .= " '".$lstData[$iFieldType]."' ";
          break;

        /**
         * without "'"
         */
        case _FIELD_TYPE_NUMBER:

          $values .= " ".$lstData[$iFieldType]." ";
          break;

        /**
         * error
         */
        default:
          $this->ErrHdl->usrDie("Error: Invalid FieldType ".$lstFieldType[$iFieldType]." ");
      }

      $values .= $this->addComma($iFieldType, $szFieldType);
    }

    $query .= ") VALUES(".$values.") ";

    $Db->execQuery($query);
  }
}

?>